﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JSC.Portal.Services;
using System.Web.Mvc;
using JSC.Portal.Entities;
using NHibernate;
using JSC.Portal.Web.Helper;
using JSC.Data.NHibernate;

namespace JSC.Portal.Web.Controllers
{
    [Authorize(Roles = "Administrator,SiteAdministrator")]
    [HandleError]
    public class ModuleTypesController : ServicedController<IModuleTypeService>
    {
        public ActionResult List()
        {
            PortalUser u = ControllerContext.CurrentUser();
            List<ModuleType> licensedModules = (from lm in u.PortalSite.LicensedModules select lm.LicensedModule).ToList();
            IList<ModuleType> modules = (u.IsInRole(Roles.Administrator)) ? Service.GetAll() : licensedModules;
            return View(modules);
        }

        public ActionResult Edit(int id)
        {
            ModuleType mt = Service.GetById(id, false);
            return View(mt);
        }

        public ActionResult SaveOrUpdate(int id, string name, string description, string assemblyname, string classname
            , string controllername, string viewname)
        {
            using (ITransaction trans = NHibernateSession.Current.BeginTransaction())
            {
                ModuleType mt = Service.GetById(id, false, true);
                mt.Name = name;
                mt.Description = description;
                mt.AssemblyName = assemblyname;
                mt.ClassName = classname;
                mt.ControllerName = controllername;
                mt.ViewName = viewname;
                mt = Service.SaveOrUpdate(mt);
                trans.Commit();
                return RedirectToAction("Edit", new { id = mt.Id });
            }
        }

        public ActionResult Create(int id)
        {
            ModuleType mt = new ModuleType();
            return View("Edit", mt);
        }

        public ActionResult Delete(int id)
        {
            using (ITransaction trans = NHibernateSession.Current.BeginTransaction())
            {
                ModuleType mt = Service.GetById(id, false);
                Service.Delete(mt);
                trans.Commit();
                return RedirectToAction("List");
            }
        }
    }
}
